<template>
  <div class="basic-layout">
    <!-- 顶部导航栏 -->
    <el-header class="layout-header" height="60px">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.svg" alt="苒兴教育" class="logo-img" />
          <span class="logo-text">苒兴教育</span>
        </div>
        
        <!-- 主导航菜单 -->
        <el-menu
          :default-active="activeMenu"
          mode="horizontal"
          class="header-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="/dashboard">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="/courses">
            <el-icon><Reading /></el-icon>
            <span>我的课程</span>
          </el-menu-item>
          <el-menu-item index="/exams">
            <el-icon><EditPen /></el-icon>
            <span>考试练习</span>
          </el-menu-item>
          <el-menu-item index="/study-plan">
            <el-icon><Calendar /></el-icon>
            <span>学习计划</span>
          </el-menu-item>
          <el-menu-item index="/progress">
            <el-icon><TrendCharts /></el-icon>
            <span>学习进度</span>
          </el-menu-item>
        </el-menu>
      </div>
      
      <div class="header-right">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程、考试..."
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-icon class="search-icon" @click="handleSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 消息通知 -->
        <el-dropdown trigger="click" @command="handleNotificationCommand">
          <div class="notification-btn">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0">
              <el-icon size="20"><Bell /></el-icon>
            </el-badge>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <div class="notification-header">
                <span>消息通知</span>
                <el-button text size="small" @click="markAllAsRead">全部已读</el-button>
              </div>
              <div class="notification-list">
                <div
                  v-for="notification in notifications"
                  :key="notification.id"
                  class="notification-item"
                  :class="{ unread: !notification.read }"
                  @click="handleNotificationClick(notification)"
                >
                  <div class="notification-content">
                    <div class="notification-title">{{ notification.title }}</div>
                    <div class="notification-desc">{{ notification.content }}</div>
                    <div class="notification-time">{{ formatTime(notification.createdAt) }}</div>
                  </div>
                </div>
              </div>
              <div class="notification-footer">
                <el-button text @click="$router.push('/notifications')">查看全部</el-button>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 用户菜单 -->
        <el-dropdown trigger="click" @command="handleUserCommand">
          <div class="user-info">
            <el-avatar :src="userStore.avatar" :size="32">
              {{ userStore.name?.charAt(0) }}
            </el-avatar>
            <span class="user-name">{{ userStore.name }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                设置
              </el-dropdown-item>
              <el-dropdown-item command="help">
                <el-icon><QuestionFilled /></el-icon>
                帮助中心
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container" v-if="showBreadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="item in breadcrumbList"
          :key="item.path"
          :to="item.path"
        >
          {{ item.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 主内容区域 -->
    <el-main class="layout-main">
      <router-view v-slot="{ Component, route }">
        <transition name="fade-transform" mode="out-in">
          <keep-alive :include="cachedViews">
            <component :is="Component" :key="route.path" />
          </keep-alive>
        </transition>
      </router-view>
    </el-main>
    
    <!-- 回到顶部 -->
    <el-backtop :right="30" :bottom="30" />
    
    <!-- 全局加载遮罩 -->
    <div v-if="appStore.loading" class="global-loading">
      <el-loading-spinner size="large" />
      <p>{{ appStore.loadingText }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House, Reading, EditPen, Calendar, TrendCharts,
  Search, Bell, User, Setting, QuestionFilled,
  SwitchButton, ArrowDown
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { useAppStore } from '@/store/app'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const appStore = useAppStore()

// 响应式数据
const searchKeyword = ref('')
const notifications = ref([])
const unreadCount = ref(0)
const cachedViews = ref(['Dashboard', 'CourseList', 'CourseDetail'])

// 计算属性
const activeMenu = computed(() => {
  const path = route.path
  if (path.startsWith('/courses')) return '/courses'
  if (path.startsWith('/exams')) return '/exams'
  if (path.startsWith('/study-plan')) return '/study-plan'
  if (path.startsWith('/progress')) return '/progress'
  return '/dashboard'
})

const breadcrumbList = computed(() => {
  return appStore.breadcrumbList
})

const showBreadcrumb = computed(() => {
  return breadcrumbList.value.length > 1
})

// 方法
const handleMenuSelect = (index) => {
  if (index !== route.path) {
    router.push(index)
  }
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { keyword: searchKeyword.value }
    })
  }
}

const handleNotificationCommand = (command) => {
  // 处理通知相关命令
}

const handleNotificationClick = (notification) => {
  // 标记为已读
  if (!notification.read) {
    notification.read = true
    unreadCount.value--
  }
  
  // 跳转到相关页面
  if (notification.link) {
    router.push(notification.link)
  }
}

const markAllAsRead = () => {
  notifications.value.forEach(item => {
    item.read = true
  })
  unreadCount.value = 0
}

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'help':
      router.push('/help')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await userStore.logout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        // 用户取消
      }
      break
  }
}

const formatTime = (time) => {
  const now = new Date()
  const target = new Date(time)
  const diff = now - target
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return target.toLocaleDateString()
  }
}

const loadNotifications = async () => {
  try {
    // 这里应该调用API获取通知
    // const data = await getNotifications()
    // notifications.value = data.list
    // unreadCount.value = data.unreadCount
    
    // 模拟数据
    notifications.value = [
      {
        id: 1,
        title: '新课程上线',
        content: 'Vue3进阶课程已上线，快来学习吧！',
        read: false,
        createdAt: new Date(Date.now() - 3600000),
        link: '/courses/vue3-advanced'
      },
      {
        id: 2,
        title: '考试提醒',
        content: 'JavaScript基础考试将在明天开始',
        read: false,
        createdAt: new Date(Date.now() - 7200000),
        link: '/exams/js-basic'
      }
    ]
    unreadCount.value = notifications.value.filter(item => !item.read).length
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

// 监听路由变化更新面包屑
watch(
  () => route.path,
  () => {
    appStore.updateBreadcrumb(route)
  },
  { immediate: true }
)

// 生命周期
onMounted(() => {
  loadNotifications()
  
  // 定期检查通知
  setInterval(loadNotifications, 5 * 60 * 1000) // 5分钟检查一次
})
</script>

<style lang="scss" scoped>
.basic-layout {
  min-height: 100vh;
  background-color: var(--el-bg-color-page);
}

.layout-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
  
  .logo {
    display: flex;
    align-items: center;
    margin-right: 40px;
    
    .logo-img {
      width: 32px;
      height: 32px;
      margin-right: 8px;
    }
    
    .logo-text {
      font-size: 18px;
      font-weight: 600;
      color: var(--el-color-primary);
    }
  }
  
  .header-menu {
    border-bottom: none;
    
    :deep(.el-menu-item) {
      border-bottom: 2px solid transparent;
      
      &.is-active {
        border-bottom-color: var(--el-color-primary);
        color: var(--el-color-primary);
      }
    }
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
  
  .search-box {
    .search-input {
      width: 240px;
    }
    
    .search-icon {
      cursor: pointer;
      color: var(--el-text-color-placeholder);
      
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
  
  .notification-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: var(--el-fill-color-light);
    }
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 20px;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: var(--el-fill-color-light);
    }
    
    .user-name {
      font-size: 14px;
      color: var(--el-text-color-primary);
    }
  }
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  font-weight: 600;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid var(--el-border-color-lighter);
  transition: background-color 0.3s;
  
  &:hover {
    background-color: var(--el-fill-color-light);
  }
  
  &.unread {
    background-color: var(--el-color-primary-light-9);
    
    .notification-title {
      font-weight: 600;
    }
  }
  
  .notification-content {
    .notification-title {
      font-size: 14px;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .notification-desc {
      font-size: 12px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }
    
    .notification-time {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
}

.notification-footer {
  padding: 8px 16px;
  text-align: center;
  border-top: 1px solid var(--el-border-color-lighter);
}

.breadcrumb-container {
  padding: 12px 20px;
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.layout-main {
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  p {
    margin-top: 16px;
    color: var(--el-text-color-regular);
  }
}

// 过渡动画
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

// 响应式设计
@media (max-width: 768px) {
  .header-left {
    .logo {
      margin-right: 20px;
      
      .logo-text {
        display: none;
      }
    }
    
    .header-menu {
      display: none;
    }
  }
  
  .header-right {
    .search-box {
      .search-input {
        width: 180px;
      }
    }
    
    .user-info {
      .user-name {
        display: none;
      }
    }
  }
  
  .layout-main {
    padding: 12px;
  }
}
</style>